<template>
  <div class="admin-management">
    <div class="page-header">
      <h1>管理员设置</h1>
      <p>管理系统中的后台登录账户</p>
    </div>

    <!-- 操作区域 -->
    <div class="operation-bar">
      <div class="search-area">
        <el-input
          v-model="searchForm.username"
          placeholder="请输入用户名搜索"
          style="width: 300px"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="handleSearch" :loading="loading">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>

      <div class="action-area">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增管理员
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="username" label="用户名" min-width="150" />

        <el-table-column prop="is_super_admin" label="超级管理员" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_super_admin ? 'danger' : 'info'" size="small">
              {{ row.is_super_admin ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="is_active" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updated_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="row.id === userStore.userInfo?.id"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            :placeholder="isEdit ? '留空则不修改密码' : '请输入密码'"
            show-password
          />
        </el-form-item>

        <el-form-item label="超级管理员" prop="is_super_admin">
          <el-switch
            v-model="formData.is_super_admin"
            :disabled="isEdit && currentEditId === userStore.userInfo?.id"
          />
          <div class="form-tip">超级管理员拥有所有权限</div>
        </el-form-item>

        <el-form-item label="账户状态" prop="is_active">
          <el-switch
            v-model="formData.is_active"
            :disabled="isEdit && currentEditId === userStore.userInfo?.id"
          />
          <div class="form-tip">禁用后将无法登录系统</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ submitLoading ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import {
  getAdmins,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  type Admin,
  type CreateAdminParams,
  type UpdateAdminParams
} from '@/api/permission'

// 状态管理
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<Admin[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentEditId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive({
  username: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单引用和数据
const formRef = ref<FormInstance>()
const formData = reactive<CreateAdminParams & UpdateAdminParams>({
  username: '',
  password: '',
  is_super_admin: false,
  is_active: true
})

// 表单验证规则
const formRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!isEdit.value && !value) {
          callback(new Error('请输入密码'))
        } else if (value && value.length < 6) {
          callback(new Error('密码长度至少6个字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑管理员' : '新增管理员')

// 方法定义
/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

/**
 * 加载管理员列表
 */
async function loadAdmins() {
  try {
    loading.value = true

    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      username: searchForm.username.trim() || undefined
    }

    const response = await getAdmins(params)

    if (response.success) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('加载管理员列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 */
function handleSearch() {
  pagination.page = 1
  loadAdmins()
}

/**
 * 分页大小改变
 */
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  loadAdmins()
}

/**
 * 当前页改变
 */
function handleCurrentChange(page: number) {
  pagination.page = page
  loadAdmins()
}

/**
 * 新增管理员
 */
function handleAdd() {
  isEdit.value = false
  currentEditId.value = null
  resetForm()
  dialogVisible.value = true
}

/**
 * 编辑管理员
 */
function handleEdit(row: Admin) {
  isEdit.value = true
  currentEditId.value = row.id

  Object.assign(formData, {
    username: row.username,
    password: '',
    is_super_admin: !!row.is_super_admin,
    is_active: !!row.is_active
  })

  dialogVisible.value = true
}

/**
 * 删除管理员
 */
async function handleDelete(row: Admin) {
  try {
    await ElMessageBox.confirm(
      `确定要删除管理员"${row.username}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteAdmin(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadAdmins()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 提交表单
 */
async function handleSubmit() {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    submitLoading.value = true

    // 准备提交数据
    const submitData = {
      username: formData.username,
      is_super_admin: formData.is_super_admin,
      is_active: formData.is_active
    } as any

    // 只有在密码不为空时才包含密码字段
    if (formData.password) {
      submitData.password = formData.password
    }

    if (isEdit.value && currentEditId.value) {
      // 更新
      const response = await updateAdmin(currentEditId.value, submitData)
      if (response.success) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        loadAdmins()
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 创建
      const response = await createAdmin(submitData)
      if (response.success) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        loadAdmins()
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

/**
 * 重置表单
 */
function resetForm() {
  Object.assign(formData, {
    username: '',
    password: '',
    is_super_admin: false,
    is_active: true
  })

  if (formRef.value) {
    formRef.value.resetFields()
  }
}

/**
 * 对话框关闭处理
 */
function handleDialogClose() {
  resetForm()
}

// 生命周期
onMounted(() => {
  loadAdmins()
})
</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    gap: 15px;
  }

  .search-area {
    width: 100%;
  }

  .search-area .el-input {
    width: 100% !important;
  }
}
</style>
